import Request from '@/js_sdk/luch-request/request.js'
import { showTipsToast, showErrorToast, requestEncodeMsg, showLoading, hideLoading } from '@/common/utils.js'
import {BASE_URL} from '@/store/constant'

export const http = new Request()

http.setConfig((config) => { /* 设置全局配置 */
  config.baseUrl = BASE_URL /* 根域名不同 */
  // config.baseUrl = ''
  config.header = {
    'content-type': 'application/x-www-form-urlencoded'
    // 'content-type': 'application/json; charset=utf-8'
    // 'authorization-token': ''
  }
  return config
})

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  // console.log('请求拦截器', config)
  // const { url, data } = config
  const token = uni.getStorageSync('ACCESS_TOKEN') || ''
  
  // if (!ifNoNeedToken(url) && !token) { // 请求需要token, 且token不存在，调用cancel 会取消本次请求，但是该函数的catch() 仍会执行
  //   cancel('token 不存在')
  //   return
  // }
  
  uni.hideKeyboard()
  showLoading()
  config.header = {
    'authorization-token': token,
    ...config.header
  }
  
  return config
})

http.interceptor.response((response) => { /* 请求之后拦截器 */
  // console.log('请求响应拦截器', response)
  hideLoading(600)
  const responseData = response.data
  let resData = null
  if (typeof responseData === 'string') {
    const stringData = responseData.replace(new RegExp('\\\\','g'), "")
    resData = JSON.parse(stringData)
  } else {
    resData = responseData
  }
  const { code, msg } = resData

  let errMsg = msg || '请求错误'

  if (code === 0) {
    return resData
  } else {
    showTipsToast(errMsg)
    return null
  }
}, (response) => { // 请求错误做点什么
  hideLoading(600)
  showErrorToast('请稍后重试')
  return response
})

export const getRequest = (url, params) => {
  return new Promise((resolve, reject) => {
    http.get(url, {params}).then(res => {
      resolve(res)
    }).catch((err) => {
      console.log('get异常: ', err)
      reject()
      uni.stopPullDownRefresh()
    })
  })
}

export const postRequest = (url, params) => {
  return new Promise((resolve, reject) => {
    http.post(url, params).then(res => {
      resolve(res)
    }).catch((err) => {
      console.log('post异常: ', err)
      reject()
      uni.stopPullDownRefresh()
    })
  })
}

export const uploadRequest = (url, params) => {
  return new Promise((resolve, reject) => {
    http.upload(url, params).then(res => {
      resolve(res)
    }).catch((err) => {
      console.log('post异常: ', err)
      reject()
      uni.stopPullDownRefresh()
    })
  })
}
